package com.lulin.mall.search.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lulin.common.dto.es.SkuEsModel;
import com.lulin.mall.search.config.ElasticSearchConfiguration;
import com.lulin.mall.search.constant.ESConstant;
import com.lulin.mall.search.service.ElasticSearchSaveService;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * @author lulin
 * @date 2022/11/11 18:01
 */
@Service
public class ElasticSearchSaveServiceImpl implements ElasticSearchSaveService {

    @Autowired
    RestHighLevelClient client;

    /**
     * 商品上架数据保存到es服务器
     *
     * @param skuEsModels
     * @return
     */
    @Override
    public Boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
        //创建对应的索引库——>创建对应的product的映射
        //BulkRequest bulkRequest, RequestOptions options
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            //绑定对应的索引库 product
            IndexRequest indexRequest = new IndexRequest(ESConstant.PRODUCT_INDEX);
            //设置id
            indexRequest.id(skuEsModel.getSkuId().toString());
            //设置文档
            //用Jackson中的对象，转json数据
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(skuEsModel);
            indexRequest.source(json, XContentType.JSON);
            //转换后的数据，封装到Bulk中
            bulkRequest.add(indexRequest);

        }
        //批量向Es中，保存数据
        BulkResponse bulk = client.bulk(bulkRequest, ElasticSearchConfiguration.COMMON_OPTIONS);
        //判断批量操作是有错误
        boolean b = bulk.hasFailures();
       /* //可以获取很多信息
        for (BulkItemResponse item : bulk.getItems()) {

        }*/
        //没有错误，取反
        return !b;
    }
}
